//
//  LWS_SearchViewController.m
//  Lws___
//
//  Created by dllo on 16/3/16.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "LWS_SearchViewController.h"
#import "LWS_ Classifymodel.h"
#import "LWS_GiftHxmIViewController.h"
#import "LWS_SelectTitleCollectionViewCell.h"
#import "LWS_GiftJumpViewController.h"
@interface LWS_SearchViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UISearchBarDelegate>
@property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
@property (strong, nonatomic) IBOutlet UICollectionView *searchCollectionView;
@property (strong, nonatomic) IBOutlet UICollectionViewFlowLayout *searchFlowLayout;
@property (strong, nonatomic) NSMutableArray *hot_wordsArr;
@property (nonatomic, retain) NSString *str;
@property (nonatomic, retain) NSMutableArray *searchArr;
- (IBAction)searchButton:(id)sender;
@property (nonatomic, retain) NSMutableArray *posts_Arr;

@end

@implementation LWS_SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:1.000 green:0.445 blue:0.525 alpha:1.000];
//    self.navigationController.navigationBar.translucent = NO;
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui.png"] style:1 target:self action:@selector(returnB)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    [self.searchCollectionView setCollectionViewLayout:self.searchFlowLayout];
    [self.navigationController.view addSubview:self.searchBar];
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.left.mas_equalTo(50);
        make.width.mas_equalTo(320);
        make.height.mas_equalTo(35);
        
        
    }];
    
    [self.searchCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([LWS_SelectTitleCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([LWS_SelectTitleCollectionViewCell class])];
    
    self.searchCollectionView.backgroundColor = [UIColor whiteColor];
    [self createNetWork];
    
}

#pragma mark 获取网络数据
-(void)createNetWork{


    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:@"http://api.liwushuo.com/v2/search/hot_words" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
       self.hot_wordsArr = responseObject[@"data"][@"hot_words"];
       
       
        [self.searchCollectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
    
    
    

}
#pragma mark 取消搜索框第一响应者
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{

    [self.searchBar resignFirstResponder];

}

#pragma mark 时时刷新
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
        AFHTTPSessionManager *success = [AFHTTPSessionManager manager];
        NSString *str =[searchText stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:searchText]];
        //    %E6%8D%AE
        [success GET:[NSString stringWithFormat:@"http://api.liwushuo.com/v2/search/item?keyword=%@&limit=20&offset=0&sort=",str] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSMutableArray *itemArr = responseObject[@"data"][@"items"];
            self.searchArr = [NSMutableArray array];
            for (NSDictionary *dic in itemArr) {
                LWS__Classifymodel *model = [[LWS__Classifymodel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.searchArr addObject:model];
                
            }
            
            [self.searchCollectionView reloadData];
            
            if (![searchText isEqualToString:@""]) {
                
                LWS_GiftHxmIViewController *jump = [[LWS_GiftHxmIViewController alloc] initWithNibName:NSStringFromClass([LWS_GiftHxmIViewController class]) bundle:nil];
                
                [self.navigationController pushViewController:jump animated:YES];
                jump.from = str;
                
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            
        }];

    }


#pragma mark 返回按钮方法
-(void)returnB{

    [self.navigationController popViewControllerAnimated:YES];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"return" object:nil];
    self.searchBar.hidden = YES;
    
}
#pragma mark colletcionView次数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return self.hot_wordsArr.count;

}

#pragma mark collectionView重用
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    LWS_SelectTitleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LWS_SelectTitleCollectionViewCell class]) forIndexPath:indexPath];
    cell.titleLabel.text = self.hot_wordsArr[indexPath.row];
    
   
    
    
    
    cell.layer.borderWidth = 1;
    cell.titleLabel.textAlignment = 1;
    cell.titleLabel.font = [UIFont systemFontOfSize:15];
    return cell;

}
#pragma mark 自定义item大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    if ([self.hot_wordsArr[indexPath.row] length] == 2) {
        return CGSizeMake(51, 30);
    }else if([self.hot_wordsArr[indexPath.row] length] == 3){
     return CGSizeMake(68, 30);
    
    }else{
    return CGSizeMake(85, 30);
    
    }

}

#pragma mark colletcionView点击方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    LWS_GiftHxmIViewController *giftHxm = [[LWS_GiftHxmIViewController alloc]initWithNibName:NSStringFromClass([LWS_GiftHxmIViewController class]) bundle:nil];
    [self.navigationController pushViewController:giftHxm animated:YES];
//    NSString *str =[self.str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:self.str]];
//    giftHxm.from = str;
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)searchButton:(id)sender {
    
    LWS_GiftHxmIViewController *search = [[LWS_GiftHxmIViewController alloc] initWithNibName:NSStringFromClass([LWS_GiftHxmIViewController class]) bundle:nil];
    [self.navigationController pushViewController:search animated:YES];
    
    
}

@end
